﻿import stripe
from fastapi.encoders import jsonable_encoder

from odoo.addons.fastapi_odoo_bridge.core.basemodel import CommonResponse
from odoo.addons.rp_shipment_management.functions.ship_order_fc import ShipOrderFC
from ..basemodels.vo.common.sec_level import MailRoute
from ..basemodels.vo.common.trd_level import Aging, ValueAdded, RPSalePriceAdjust
from ..basemodels.vo.step.step_level import AvailableMailRoute, AvailableValueAdded
from functional import seq
from odoo.addons.basic_configuration.config.env_config import switch_env

"""
Belong:新UI
Description:下单逻辑Func
"""


class RouterFunc(object):
    """
   下单逻辑Func
    """

    # 修改某一步，清除部分步骤
    remove_mapping = {
        ('one', 'two'): {
            # 邮路信息清除
            'shipper_mail_route_id': False,
            'express_category': False,
            'same_city_flag': False,
            'same_province_flag': False,
            'shipper_id': False,
            'aging_id': False,
            'expect_arrive_date': False,
            'used_sale_price_adjust_ids': False,
            'used_coupon_ids_for_mail': False,
            # 头尾程信息,增值服务清除
            'fulfillment_dropoff': False,
            'fulfillment_pickup': False,
            'fulfillment_collect': False,
            'fulfillment_delivery': False,
            'rp_ship_order_fulfillment_line_ids': [(6, 0, [])],
            'rp_ship_order_value_added_line_ids': [(6, 0, [])],
            'select_value_added_line_ids': [(6, 0, [])],
            # 价格修改
            'mail_route_tag_price': False,  # 邮路标价
            'mail_route_sale_adjusted_price': False,  # 邮路销售调后价
            'mail_route_actual_price': False,  # 邮路实价
            'fulfillment_total_tag_price': False,  # 头尾程标价
            'fulfillment_total_sale_adjusted_price': False,  # 头尾程总调后价
            'fulfillment_total_actual_price': False,  # 头尾程总实价
            'value_added_total_tag_price': False,  # 增值服务总标价
            'value_added_total_sale_adjusted_price': False,  # 增值服务总调后价
            'value_added_total_actual_price': False,  # 增值服务总实价
            'total_tag_price': False,  # 总标价
            'total_sale_adjusted_price': False,  # 总调后价
            'total_actual_price': False,  # 总实价
            # 城市和街道清除
            'send_street': False,
            'receive_street': False
        },
        ('three',): {
            # 头尾程信息,增值服务清除
            'fulfillment_dropoff': False,
            'fulfillment_pickup': False,
            'fulfillment_collect': False,
            'fulfillment_delivery': False,
            'rp_ship_order_fulfillment_line_ids': [(6, 0, [])],
            'rp_ship_order_value_added_line_ids': [(6, 0, [])],
            'select_value_added_line_ids': [(6, 0, [])],
        }
    }

    def __init__(self, env):
        self.env = env

    """
    Common
    """

    def get_order_detail(self, order_code):
        """
        获取订单信息（此接口只用于返回游客的订单）
        """
        admin_user = self.env['rp.customer'].search([('id', '=', 1)])
        rp_ship_order = self.env['rp.ship.order'].search([('code', '=', order_code.strip()), ('customer_id', '=', admin_user.id)])
        if not rp_ship_order:
            return {
                'code': '400',
                'msg': '订单信息未找到',
                'data': []
            }
        return rp_ship_order

    def logic_delete_order(self, order_code):
        """
        逻辑删除订单
        Params:
        -order_code:订单编码
        """
        rp_ship_order_id = self.env['rp.ship.order'].search([('code', '=', order_code.strip())])
        if not rp_ship_order_id:
            return {
                'code': '400',
                'msg': '订单未找到'
            }
        # 订单逻辑删除
        rp_ship_order_id.write({'active': False})
        return {
            'code': 200,
            'msg': '删除成功'
        }

    def get_remove_value(self, step):
        """
        获取需要消除的值
        """
        step_name = step.strip()
        for key, values in self.remove_mapping.items():
            if step_name in key:
                return values

    def fill_two_value_added_data(self, list_data):
        available_value_added_list = []
        for record in list_data:
            value_added_id = record.get('value_added_id')
            value_added_type = record.get('value_added_type')
            value_added_category = record.get('value_added_category')
            tag_price = record.get('tag_price')
            sale_adjusted_price = record.get('sale_adjusted_price')
            used_sale_price_adjust_ids = record.get('used_sale_price_adjust_ids')
            # 填充数据
            value_added = None
            # 增值服务
            if value_added_id:
                value_added = self.env['rp.value.added.service'].search([('id', '=', value_added_id)])
                value_added = ValueAdded(__from_odoo=value_added, __env=self.env)
            # 使用的调价
            used_sale_price_adjust_list = []
            if used_sale_price_adjust_ids:
                price_adjustment_ids = used_sale_price_adjust_ids[0][2]
                price_adjustment_ids = self.env['rp.shipper.sale.price.adjustment'].search([('id', 'in', price_adjustment_ids)])
                for record in price_adjustment_ids:
                    price_adjust = RPSalePriceAdjust(__from_odoo=record, __env=self.env)
                    used_sale_price_adjust_list.append(price_adjust)
            available_value_added = AvailableValueAdded(value_added_type=value_added_type,
                                                        value_added_category=value_added_category, tag_price=tag_price, adjusted_price=sale_adjusted_price,
                                                        used_sale_price_adjust_ids=used_sale_price_adjust_list)
            available_value_added.valued_added_id = value_added
            available_value_added_list.append(available_value_added)
        return available_value_added_list

    def fill_one_value_added_data(self, list_data):
        available_value_added_list = []
        for record in list_data:
            value_added_id = record.get('id')
            value_added_id = self.env['rp.value.added.service'].search([('id', '=', value_added_id)])
            value_added_type = value_added_id.type
            value_added_category = value_added_id.category
            tag_price = record.get('tag_price')
            sale_adjusted_price = record.get('sale_adjusted_price')
            used_sale_price_adjust_ids = record.get('used_sale_price_adjust_ids')
            # 填充数据
            value_added = None
            # 增值服务
            if value_added_id:
                value_added = self.env['rp.value.added.service'].search([('id', '=', value_added_id.id)])
                value_added = ValueAdded(__from_odoo=value_added, __env=self.env)
            # 使用的调价
            used_sale_price_adjust_list = []
            if used_sale_price_adjust_ids:
                price_adjustment_ids = used_sale_price_adjust_ids[0][2]
                price_adjustment_ids = self.env['rp.shipper.sale.price.adjustment'].search([('id', 'in', price_adjustment_ids)])
                for record in price_adjustment_ids:
                    price_adjust = RPSalePriceAdjust(__from_odoo=record, __env=self.env)
                    used_sale_price_adjust_list.append(price_adjust)
            available_value_added = AvailableValueAdded(value_added_type=value_added_type,
                                                        value_added_category=value_added_category, tag_price=tag_price, adjusted_price=sale_adjusted_price,
                                                        used_sale_price_adjust_ids=used_sale_price_adjust_list)
            available_value_added.valued_added_id = value_added
            available_value_added_list.append(available_value_added)
        return available_value_added_list

    """
    RELATED NEW UI STEP ONE
    """

    def get_country_list(self, country_name):
        """
        获取国家列表
        【过滤国家或获取全部国家】
        """
        domain_list = []
        if country_name:
            country_name = country_name.strip()
            domain_list.append(('name', 'ilike', f"{country_name}%"))
        country_list = self.env['res.country'].with_context(lang='en_US').search(domain_list)
        if not country_list:
            return {
                'code': '400',
                'msg': '没有找到此国家数据',
                'data': []
            }
        return country_list

    def get_postcode(self, country_id, postcode_city: str):
        """
        获取邮编信息【邮编或城市模糊搜索】
        """
        country_id = self.env['res.country'].search([('id', '=', country_id)])
        if not country_id:
            return {
                'code': '400',
                'msg': '国家不存在',
                'data': []
            }
        if postcode_city:
            if not postcode_city.isdigit():
                city_list = self.env['res.city'].search([('name', 'ilike', f"{postcode_city}")])
                result = self.env['rp.postal.code'].search([('city_id', 'in', city_list.ids), ('country_id', '=', country_id.id)], limit=10)
            else:
                result = self.env['rp.postal.code'].search([('name', 'ilike', f"{postcode_city}%"), ('country_id', '=', country_id.id)], limit=10)
        else:
            result = self.env['rp.postal.code'].search([('country_id', '=', country_id.id)], limit=10)
        return result

    def get_package_type(self):
        """
        获取包裹类型
        """
        package_type_ids = self.env['rp.package.type'].search([])
        if not package_type_ids:
            return {
                'code': '400',
                'msg': '系统未配置包裹类型',
                'data': []
            }
        return package_type_ids

    """
    RELATED NEW UI STEP TWO
    """

    def get_all_courier(self):
        """
        获取所有承运商
        """
        rp_courier_ids = self.env['rp.courier'].search([])
        if len(rp_courier_ids.ids) == 0:
            return {
                'code': '400',
                'msg': '没有承运商数据',
                'data': []
            }
        return rp_courier_ids

    def get_all_value_added(self):
        """
        获取所有增值服务
        """
        value_added_list = self.env['rp.value.added.service'].search([])
        if len(value_added_list.ids) == 0:
            return {
                'code': '400',
                'msg': '没有增值服务的数据',
                'data': []
            }
        return value_added_list

    def get_all_aging(self):
        """
        获取所有时效
        """
        rp_aging_list = self.env['rp.aging'].search([])
        if len(rp_aging_list.ids) == 0:
            return {
                'code': '400',
                'msg': '没有时效数据',
                'data': []
            }
        return rp_aging_list

    def filter_available_mail_route(self, route_filter):
        """
        筛选可用邮路
        Params:
        -route_filter:筛选参数
        """
        # 获取参数
        order_code = route_filter.order_code
        send_method = route_filter.send_method
        receive_method = route_filter.receive_method
        time_form = route_filter.time_from
        time_to = route_filter.time_to
        valued_add_list = route_filter.valued_add_list
        courier_list = route_filter.courier_list
        order_by = route_filter.order_by
        # 获取订单记录
        rp_order_id = self.env['rp.ship.order'].search([('code', '=', order_code)])
        # 获取范围起点时效和范围终点时效
        rp_aging_time_from_id = self.env['rp.aging'].search([('id', '=', time_form)]) if id != 0 else False
        rp_aging_time_to_id = self.env['rp.aging'].search([('id', '=', time_to)])
        if not rp_order_id:
            return {
                'code': '400',
                'msg': '未找到订单记录'
            }
        if rp_order_id.state == 'done':
            return {
                'code': '403',
                'msg': '该订单已经完成，不支持此操作',
                'data': []
            }
        # 创建瞬态模型
        records = ShipOrderFC(self.env).backdoor_get_available_smr(send_city=rp_order_id.send_city_id,
                                                                   receive_city=rp_order_id.receive_city_id,
                                                                   package_type=rp_order_id.package_type_id,
                                                                   parcel_total_weight=rp_order_id.parcel_total_weight,
                                                                   parcel_total_volume=rp_order_id.parcel_total_volume)
        # 存在数据筛选的情况
        if route_filter:
            shipper_list = self.env['rp.courier'].search([('id', 'in', courier_list)]).mapped('shipper_id').mapped('id')

            def ft(x):
                a = True
                # 根据时效筛选【起始时效都是有效记录情况】
                if all([time_form, time_to]) and x.get('aging_id'):
                    unit_time = self.env['rp.aging'].search([('id', '=', x.get('aging_id'))]).standard_unit_time
                    if not (rp_aging_time_from_id.standard_unit_time <= unit_time <= rp_aging_time_to_id.standard_unit_time):
                        a = False
                # 根据时效筛选【起始时效为0的情况】
                if not time_form and time_to and x.get('aging_id'):
                    unit_time = self.env['rp.aging'].search([('id', '=', x.get('aging_id'))]).standard_unit_time
                    if not (unit_time <= rp_aging_time_to_id.standard_unit_time):
                        a = False
                # 根据托运商筛选
                if shipper_list and x.get('shipper_id'):
                    if x['shipper_id'] not in shipper_list:
                        a = False
                # 处理头尾程
                select_fulfillment = seq([send_method, receive_method]).filter(lambda r: r is not None and r.strip() != "")
                if select_fulfillment:
                    # 获取托运商邮路
                    shipper_mail_route = x.get('shipper_mail_route_id')
                    shipper_mail_route = self.env['rp.shipper.mail.route'].browse(shipper_mail_route)
                    mapping = {
                        'dropoff': shipper_mail_route.operation_dropoff,
                        'pickup': shipper_mail_route.operation_pickup,
                        'collect': shipper_mail_route.operation_collect,
                        'delivery': shipper_mail_route.operation_delivery,
                        'not_limit': True
                    }
                    for record in select_fulfillment:
                        for key, value in mapping.items():
                            if key.strip() == record.strip() and value is False:
                                a = False
                                break
                        if not a:
                            break
                # 根据增值服务筛选
                if valued_add_list and x.get('shipper_mail_route_id'):
                    value_add_ids = self.env['rp.shipper.mail.route'].search([('id', '=', x['shipper_mail_route_id'])]).value_added_ids.ids
                    # 查看是否为子集
                    if not set(valued_add_list).issubset(set(value_add_ids)):
                        a = False
                if a:
                    return x

            records = filter(ft, records)

        response_list = []
        for record in records:
            # 处理时效
            rp_aging = self.env['rp.aging'].search([('id', '=', record.get('aging_id'))])
            # 处理邮路
            shipper_mail_route_id = record.get('shipper_mail_route_id')
            sale_price_adjust = record.get('used_sale_price_adjust_ids')[0][2]
            mail_route = self.env['rp.shipper.mail.route'].search([('id', '=', shipper_mail_route_id)])
            # 处理增值服务
            valued_added_ids = mail_route.value_added_ids
            # 处理预计到达时间
            expect_arrive_date = record.get('expect_arrive_date')
            expect_arrive_date = expect_arrive_date.strftime("%Y-%m-%d %H:%M:%S")
            # 封装为前端格式数据
            mail_route = MailRoute(__from_odoo=mail_route, __env=self.env)
            aging = Aging(__from_odoo=rp_aging, __env=self.env)
            valued_added_list = [ValueAdded(__from_odoo=record, __env=self.env) for record in valued_added_ids]
            response = AvailableMailRoute(mail_route=mail_route, aging=aging, tag_price=record.get('tag_price'), sale_adjustment_price=record.get('sale_adjusted_price')
                                          , available_value_added=valued_added_list, available_adjustment=sale_price_adjust, expect_arrive_date=expect_arrive_date)
            response_list.append(response)
        response_data = jsonable_encoder(response_list)
        if order_by:
            if order_by.price and order_by.price == 'desc':  # 销售调后价降序排序
                response_data = sorted(response_data, key=lambda x: x['sale_adjustment_price'], reverse=True)
            elif order_by.price and order_by.price == 'asc':  # 销售调后价升序排序
                response_data = sorted(response_data, key=lambda x: x['sale_adjustment_price'], reverse=False)
            if order_by.aging and order_by.aging == 'desc':  # 时效降序排序
                response_data = sorted(response_data, key=lambda x: x['aging']['standard_unit_time'], reverse=True)
            elif order_by.aging and order_by.aging == 'asc':  # 时效升序排序
                response_data = sorted(response_data, key=lambda x: x['aging']['standard_unit_time'], reverse=False)
            if order_by.aging and order_by.aging == 'desc':  # 根据托运商名称降序排序
                response_data = sorted(response_data, key=lambda x: x['MailRoute']['Shipper']['name'], reverse=True)
            if order_by.courier and order_by.courier == 'asc':  # 根据托运商名称降序排序
                response_data = sorted(response_data, key=lambda x: x['MailRoute']['Shipper']['name'], reverse=True)
        return jsonable_encoder(CommonResponse(code='200', msg='success', data=response_data))

    """
    RELATED NEW UI STEP FIVE
    """

    def edit_address(self, edit_address):
        """
        编辑后更新地址
        Params:
        -edit_address:编辑地址
        """

        # 获取订单
        rp_ship_order_id = self.env['rp.ship.order'].search([('code', '=', edit_address.order_code)])
        if not rp_ship_order_id:
            return {
                'code': '400',
                'msg': '没有此订单',
                'data': []
            }

        def get_data(address):
            mapping = [('0', 'residential'), ('1', 'commercial')]
            address_type = None
            for key, value in mapping:
                if str(address.address_type) == key:
                    address_type = value
            return address.street, address.first_name, address.last_name, address.phone_number, address.area_code, address_type, address.email, address.company_name, address.street2

        # 地址
        send_street, send_first_name, send_last_name, send_phone_number, send_phone_area_code, send_address_type, send_email, send_company_name, send_street2 = get_data(edit_address.send_address)
        receive_street, receive_first_name, receive_last_name, receive_phone_number, receive_phone_area_code, receive_address_type, receive_email, receive_company_name, receive_street2 = get_data(edit_address.receive_address)

        values = {
            'receive_street': receive_street,
            'receive_first_name': receive_first_name,
            'receive_last_name': receive_last_name,
            'receive_phone': receive_phone_number,
            'receive_address_type': receive_address_type,
            'receive_phone_areacode': receive_phone_area_code,
            'send_street2': send_street2,
            'receive_street2': receive_street2,
            'send_email': send_email,
            'receive_email': receive_email,
            'send_street': send_street,
            'send_first_name': send_first_name,
            'send_last_name': send_last_name,
            'send_phone': send_phone_number,
            'send_phone_areacode': send_phone_area_code,
            'send_address_type': send_address_type,
            'send_company_name': send_company_name,
            'receive_company_name': receive_company_name
        }
        # 保存信息
        rp_ship_order_id.write(values)
        # 无需变动状态，添加地址后选择下一步时状态已经确定
        return jsonable_encoder(CommonResponse(code='200', msg='success', data=[]))

    """
    NEW UI STEP ONE
    """

    def order_step_one(self, login_user, from_country, to_country, from_city_postal_code, to_city_postal_code, package_type, edit_tag, order_code):
        """
        步骤一创建订单
        Params:
        -login_user:登录用户
        -from_country:起始国家
        -to_country:目的国家
        -from_city_postal_code:起始城市邮编
        -to_city_postal_code:目的城市邮编,
        -package_type:包裹类型
        -edit_tag:编辑标志
        -order_code:订单编码
        """
        values = {
            'send_country_id': from_country,
            'send_postal_code_id': from_city_postal_code,
            'receive_country_id': to_country,
            'receive_postal_code_id': to_city_postal_code,
            'package_type_id': package_type
        }
        # 用户登录时订单的客户填充为登录用户
        if login_user:
            rp_customer_id = self.env['rp.customer'].search([('id', '=', int(login_user))])
            if not rp_customer_id:
                return {
                    'code': 400,
                    'msg': '没有找到该用户',
                    'data': []
                }
            values.update({'customer_id': rp_customer_id.id})
        if not edit_tag:
            rp_ship_order_id = self.env['rp.ship.order'].create(values)
        else:
            rp_ship_order_id = self.env['rp.ship.order'].search([('code', '=', order_code.strip())])
            if not rp_ship_order_id:
                return {
                    'code': 400,
                    'msg': '修改第一步数据，传递的订单未找到',
                    'data': []
                }
            remove_values = self.get_remove_value('one')
            values.update(remove_values)
            # 清除数据，并更新数据
            rp_ship_order_id.write(values)
            rp_ship_order_id._depends_compute_step_one()  # 第一步
            rp_ship_order_id._depends_compute_step_two()  # 第二步
            rp_ship_order_id._depends_step_three()  # 第三步
            rp_ship_order_id._depends_step_four()  # 第四步
            rp_ship_order_id._depends_step_five()  # 第五步
            rp_ship_order_id._depends_step_six()  # 第六步
        rp_ship_order_id.button_change_btn_state_next_1()
        return rp_ship_order_id

    def order_step_two(self, order_code, parcel_list, edit_tag):
        """
        下单步骤二
        Params:
        -order_code:订单编号
        -parcel_list:包裹列表
        -edit_tag:修改标志
        """
        # 检查步骤一的数据是否有变化
        ship_order_id = self.env['rp.ship.order'].search([('code', '=', order_code)])
        if not ship_order_id:
            return {
                'code': 400,
                "msg": "订单不存在",
                "data": []
            }
        if ship_order_id.state == 'done':
            return {
                'code': 403,
                'msg': '订单已经完成，不允许执行此操作',
                'data': []
            }
        parcel_ids = []
        for rp_parcel_id in ship_order_id.rp_parcel_ids:
            ship_order_id.rp_parcel_ids = [(2, rp_parcel_id.id)]
        for parcel in parcel_list:
            # 单位
            weight_uom = self.env['uom.uom'].with_context(lang='en_US').search([('name', '=', 'kg')])
            length_uom = self.env['uom.uom'].with_context(lang='en_US').search([('name', '=', 'cm')])
            values = {
                'rp_ship_order_id': ship_order_id.id,
                'weight': parcel.weight,
                'weight_uom_id': weight_uom.id,
                'depth': parcel.long,
                'width': parcel.width,
                'height': parcel.height,
                'length_uom_id': length_uom.id
            }
            parcel = self.env['rp.parcel'].create([values])
            parcel_ids.append(parcel.id)
        ship_order_id.write({'rp_parcel_ids': [(6, 0, parcel_ids)]})
        if edit_tag:
            # 清除数据
            values = self.get_remove_value('two')
            ship_order_id.write(values)
            # 更新状态
            ship_order_id._depends_compute_step_two()  # 第二步
            ship_order_id._depends_step_three()  # 第三步
            ship_order_id._depends_step_four()  # 第四步
            ship_order_id._depends_step_five()  # 第五步
            ship_order_id._depends_step_six()  # 第六步
            ship_order_id._compute_state()  # 重新计算状态
        ship_order_id.button_change_btn_state_next_1()
        return ship_order_id

    """
    NEW UI STEP TWO
    """

    def order_order_three(self, order_code, mail_route_id, edit_tag):
        """
        第三步【添加选中的邮路】
        Params:
        -order_code:订单编号
        -mail_route_id:选中的邮路
        -edit_tag:修改标志
        Description:
        后台订单部分填充所选邮路，返回前端该邮路增值的所有价格信息
        """
        ship_order = self.env['rp.ship.order'].search([('code', '=', order_code)])
        if not ship_order:
            return {
                "code": "400",
                "msg": "订单不存在",
                "data": []
            }, None
        if ship_order.state == 'done':
            return {
                'code': 403,
                'msg': '订单已经完成，不允许执行此操作',
                'data': []
            }, None
        if edit_tag:
            # 清除数据
            values = self.get_remove_value('three')
            ship_order.write(values)
            ship_order._depends_step_three()  # 第三步
            ship_order._depends_step_four()  # 第四步
            ship_order._depends_step_five()  # 第五步
            ship_order._depends_step_six()  # 第六步
            ship_order._compute_state()  # 重新计算状态
        smr_values = ShipOrderFC(self.env).backdoor_get_available_smr(send_city=ship_order.send_city_id,
                                                                      receive_city=ship_order.receive_city_id,
                                                                      package_type=ship_order.package_type_id,
                                                                      parcel_total_weight=ship_order.parcel_total_weight,
                                                                      parcel_total_volume=ship_order.parcel_total_volume)
        selected_mail_route_id = None
        for smr_value in smr_values:
            if smr_value['shipper_mail_route_id'] == mail_route_id:
                ship_order.write({
                    'shipper_mail_route_id': smr_value['shipper_mail_route_id'],
                    'shipper_id': smr_value['shipper_id'],
                    'aging_id': smr_value['aging_id'],
                    'expect_arrive_date': smr_value['expect_arrive_date'],
                    'used_sale_price_adjust_ids': smr_value['used_sale_price_adjust_ids'],
                    'parcel_actual_weight': smr_value['actual_weight'],
                    'parcel_rounded_weight': smr_value['rounded_weight'],
                    'mail_route_tag_price': smr_value['tag_price'],
                    'mail_route_sale_adjusted_price': smr_value['sale_adjusted_price'],
                })
                selected_mail_route_id = smr_value['shipper_mail_route_id']

        ship_order.button_change_btn_state_next_1()
        # 返回该邮路所具备的增值服务的详细信息
        available_value_added_list = self.get_all_available_value_added(selected_mail_route_id)
        return ship_order, available_value_added_list

    def get_all_available_value_added(self, selected_mail_route_id):
        """
        获取该邮路所有的增值服务
        Params:
        -selected_mail_route:选中的邮路
        """
        selected_mail_route = self.env['rp.shipper.mail.route'].search([('id', '=', selected_mail_route_id)])
        value_added_price_list = ShipOrderFC(self.env).backdoor_get_available_sva(selected_mail_route)
        value_fulfillment_price_list = ShipOrderFC(self.env).backdoor_get_fulfillment(selected_mail_route)
        # NOTE 处理头尾程（一类增值服务）
        filtered_fulfillment = seq(value_fulfillment_price_list).filter(lambda r: r.get('available_flag')).to_list()
        available_one_value_added_list = self.fill_one_value_added_data(filtered_fulfillment)
        # NOTE 处理增值服务（二类增值服务）
        available_two_value_added_list = self.fill_two_value_added_data(value_added_price_list)
        available_value_added_list = available_one_value_added_list + available_two_value_added_list
        return available_value_added_list

    """
    NEW UI STEP THREE
    """

    def order_step4(self, order_four):
        """
        填充包裹详情和增值服务
        """
        # 获取参数
        order_code = order_four.order_code  # 订单code
        mail_route_id = order_four.mail_route_id  # 邮路ID
        parcel_list = order_four.parcel_list  # 包裹列表
        value_added_list = order_four.value_added_list.two_category  # 所选增值列表
        fulfillment_list = order_four.value_added_list.one_category  # 所选头尾程
        rp_ship_order_id = self.env['rp.ship.order'].search([('code', '=', order_code)])
        if not rp_ship_order_id:
            return {
                'code': 400,
                'msg': '订单不存在',
                'data': []
            }
        if rp_ship_order_id.state == 'done':
            return {
                'code': 403,
                'msg': '订单已经完成，不允许执行此操作',
                'data': []
            }

        # 如果是编辑更新，需要先把增值服务清除
        if order_four.edit_tag:
            rp_ship_order_id.write({'rp_ship_order_value_added_line_ids': False, 'select_value_added_line_ids': False})
            rp_ship_order_id._depends_step_three()  # 添加默认头尾程
            rp_ship_order_id._depends_step_four()
            rp_ship_order_id._depends_step_five()
            rp_ship_order_id._depends_step_six()
            rp_ship_order_id._compute_state()  # 重新计算状态

        # 触发获取增值的模型
        shipper_mail_route = self.env['rp.shipper.mail.route'].search([('id', '=', mail_route_id)])
        available_added_and_adjusted_price_list = ShipOrderFC(self.env).backdoor_get_available_sva(shipper_mail_route)
        selected_added_and_adjusted_price_list = seq(available_added_and_adjusted_price_list).filter(lambda r: r.get('value_added_id') in value_added_list).to_list()

        # 处理默认的头尾程信息
        available_fulfillment_and_adjusted_price_list = ShipOrderFC(self.env).backdoor_get_fulfillment(shipper_mail_route)
        available_fulfillment_and_adjusted_price_list = seq(available_fulfillment_and_adjusted_price_list).filter(lambda r: r.get('available_flag')).to_list()
        selected_fulfillment_and_adjusted_price_list = seq(available_fulfillment_and_adjusted_price_list).filter(lambda r: r.get('id') in fulfillment_list).to_list()
        if len(fulfillment_list) == 2 and len(selected_fulfillment_and_adjusted_price_list) < 2:
            return {
                'code': 403,
                'msg': '选中的头程或尾程该邮路并不支持',
                'data': []
            }
        fulfillment_name_list = seq(selected_fulfillment_and_adjusted_price_list).map(lambda r: r.get('operation_type')).to_list()
        # 数据校验
        # 大于2【错误】和等于2【部分错误】
        if len(fulfillment_name_list) > 2 or set(fulfillment_name_list) == {'dropoff', 'pickup'} or set(fulfillment_name_list) == {'collect', 'delivery'}:
            return {
                'code': 403,
                'msg': '传递的头尾程错误',
                'data': []
            }
        # 头程校验
        head_fulfillment = seq(selected_fulfillment_and_adjusted_price_list).filter(lambda r: r.get('operation_type') in ['dropoff', 'pickup']).to_list()
        if len(head_fulfillment) == 0:
            return {
                'code': 403,
                'msg': '头程未传递',
                'data': []
            }
        tail_fulfillment = seq(selected_fulfillment_and_adjusted_price_list).filter(lambda r: r.get('operation_type') in ['collect', 'delivery']).to_list()
        if len(tail_fulfillment) == 0:
            return {
                'code': 403,
                'msg': '尾程未传递',
                'data': []
            }
        # 头程和尾程都选的情况,清除后台默认头尾程，填充用户选中的头尾程
        if head_fulfillment and tail_fulfillment:
            # 先清除默认的头尾程
            rp_ship_order_id.write({'fulfillment_pickup': False, 'fulfillment_collect': False, 'fulfillment_dropoff': False, 'fulfillment_delivery': False})
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_dropoff()
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_pickup()
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_delivery()
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_collect()
            # 填充用户选中的头尾程
            head_fulfillment_name = head_fulfillment[0].get('operation_type').strip()
            tail_fulfillment_name = tail_fulfillment[0].get('operation_type').strip()
            rp_ship_order_id.write({f'fulfillment_{head_fulfillment_name}': True, f'fulfillment_{tail_fulfillment_name}': True})
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_dropoff()
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_pickup()
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_delivery()
            rp_ship_order_id.with_context({'edit': True})._onchange_fulfillment_collect()

        # 处理增值服务
        used_value_added_rcds = rp_ship_order_id.rp_ship_order_value_added_line_ids.mapped('value_added_id')  # 订单已存在的增值
        need_push_record = seq(selected_added_and_adjusted_price_list).filter(lambda r: r.get('value_added_id') not in used_value_added_rcds.ids).map(lambda r: (0, 0, r)).to_list()  # 订单未存在的增值
        rp_ship_order_id.write({'rp_ship_order_value_added_line_ids': need_push_record})
        # 填充所选的增值服务
        rp_ship_order_id._onchange_rp_ship_order_value_added_line_ids()
        # 填充包裹价值和描述
        for record in parcel_list:
            id = record.id
            values = record.values
            desc = record.desc
            rp_parcel = self.env['rp.parcel'].search([('id', '=', id)])
            rp_parcel.write({
                'values': values,
                'desc': desc
            })
        # 下一步按钮
        rp_ship_order_id.button_change_btn_state_next_1()
        return rp_ship_order_id

    """
    NEW UI STEP FOUR
    """

    def order_step5(self, order_five):
        """
        下单第五步【填充地址信息】
        """

        invoice_tag = order_five.invoice_tag
        copy_from_sender = order_five.copy_from_sender

        def get_data(address):
            mapping = [('0', 'residential'), ('1', 'commercial')]
            address_type = None
            for key, value in mapping:
                if str(address.address_type) == key:
                    address_type = value
            return address.street, address.first_name, address.last_name, address.phone_number, address.area_code, address_type, address.email, address.company_name, address.street2

        # 地址
        send_street, send_first_name, send_last_name, send_phone_number, send_phone_area_code, send_address_type, send_email, send_company_name, send_street2 = get_data(order_five.send_address)
        receive_street, receive_first_name, receive_last_name, receive_phone_number, receive_phone_area_code, receive_address_type, receive_email, receive_company_name, receive_street2 = get_data(order_five.receive_address)
        invoice_receive_street, invoice_first_name, invoice_last_name, invoice_phone_number, invoice_phone_area_code, invoice_address_type, invoice_email, invoice_company_name, invoice_receive_street2 = get_data(order_five.receive_address)

        # 获取订单CODE
        order_code = order_five.order_code
        ship_order_id = self.env['rp.ship.order'].search([('code', '=', order_code)])
        if not ship_order_id:
            return {
                'code': 400,
                'msg': '订单不存在',
                'data': []
            }
        if ship_order_id.state == 'done':
            return {
                'code': 403,
                'msg': '订单已经完成，不允许执行此操作',
                'data': []
            }

        values = {
            'receive_street': receive_street,
            'receive_first_name': receive_first_name,
            'receive_last_name': receive_last_name,
            'receive_phone': receive_phone_number,
            'receive_address_type': receive_address_type,
            'receive_phone_areacode': receive_phone_area_code,
            'receive_street2': receive_street2,
            'send_email': send_email,
            'receive_email': receive_email,
            'send_street': send_street,
            'send_street2': send_street2,
            'send_first_name': send_first_name,
            'send_last_name': send_last_name,
            'send_phone': send_phone_number,
            'send_phone_areacode': send_phone_area_code,
            'send_address_type': send_address_type,
            'send_company_name': send_company_name,
            'invoice_postal_code_id': order_five.invoice_address.invoice_postal_code_id,
            'receive_company_name': receive_company_name,
            'invoice_receive_street': invoice_receive_street,
            'invoice_first_name': invoice_first_name,
            'invoice_last_name': invoice_last_name,
            'invoice_phone_number': invoice_phone_number,
            'invoice_phone_areacode': invoice_phone_area_code,
            'invoice_address_type': invoice_address_type,
            'invoice_receive_street2': invoice_receive_street2,
            'invoice_email': invoice_email,
            'copy_from_sender': copy_from_sender,
            'invoice_company_name': invoice_company_name,
            'need_invoice': invoice_tag
        }

        ship_order_id.write(values)
        # 更新状态
        ship_order_id._depends_step_five()
        ship_order_id._depends_step_six()
        ship_order_id._compute_state()  # 重新计算状态
        # 下一步按钮
        ship_order_id.button_change_btn_state_next_1()
        return ship_order_id

    """
    NEW UI STEP FIVE
    """

    def order_step6(self, step_six):
        """
        Params:
        -pay_mode-【0 其他支付方式 1 stripe支付】
        """
        pay_mode = step_six.pay_mode
        order_code = step_six.order_code
        if pay_mode != 1:
            return {
                'code': 403,
                'msg': '暂不支持着这种支付方式',
                'data': []
            }
        # 获取订单
        rp_ship_order_id = self.env['rp.ship.order'].search([('code', '=', order_code)])
        if not rp_ship_order_id:
            return {
                'code': 400,
                'msg': '订单未找到',
                'data': []
            }
        # 订单完成
        rp_ship_order_id.button_change_state_finish()
        # 生成支付单
        ShipOrderFC(self.env).gene_payment(rp_ship_order_id)
        # 调用后台支付接口（成功回调和失败回调在后台）
        link = '{}:{}/qr_code/pay?order_id={}&balance_price={}&stripe_price={}&total_price={}'.format(switch_env.get('env').get('ip'), switch_env.get('env').get('port'), rp_ship_order_id.id
                                                                                                      , 0.0, rp_ship_order_id.total_actual_price, rp_ship_order_id.total_actual_price)
        # 填充订单的支付链接
        rp_ship_order_id.write({'pay_link': link})
        return link
